package com.hn.vue.security;

import com.hn.vue.pojo.Menu;
import com.hn.vue.pojo.User;
import com.hn.vue.service.MenuService;
import com.hn.vue.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * hanni
 * 2019/3/8 0008
 * 10:48
 */
public class HnUserDetailsService implements UserDetailsService {


    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        try{

            User user = userService.findUserByName(username);//根据用户名查询用户信息
            HnUser hnUser = new HnUser();

            //根据用户名去查询权限信息
            List<Menu>  menuList = menuService.findMenusByUsername(username);
            if(CollectionUtils.isNotEmpty(menuList)){
                List<GrantedAuthority> authorities = new ArrayList<>();
                for (Menu menu : menuList) {
                    if(StringUtils.isNotEmpty(menu.getPerms())){
                        authorities.add(new SimpleGrantedAuthority(menu.getPerms()));
                    }
                }
                hnUser.setAuthorities(authorities);
            }
            //拷贝对象 参数一是：目标对象；参数二:被拷贝的对象
            BeanUtils.copyProperties(hnUser,user);
            hnUser.getAuthorities();
            return hnUser;
        }catch (Exception e){
            throw  new UsernameNotFoundException("账号不存在.........");
        }

    }
}
